package com.stockz.core.dao.hsql;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.stockz.core.dao.ScripDao;
import com.stockz.core.model.Scrip;

@Repository
@Transactional
public class ScripDaoImpl implements ScripDao {
	
	private EntityManager entityManager;
	
	@PersistenceContext
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }
	
	@Transactional(propagation=Propagation.MANDATORY, readOnly=true)
	public Scrip getScrip(String code) {
		return entityManager.find(Scrip.class, code);
	}
	
	@Transactional(propagation=Propagation.MANDATORY)
	public void persist(Scrip scrip) {
		if(scrip != null && StringUtils.hasText(scrip.getCode())){
			entityManager.persist(scrip);
			entityManager.flush();
		}
	}
	
	@SuppressWarnings("unchecked")
	@Transactional(propagation=Propagation.MANDATORY, readOnly=true)
	public List<Scrip> getAllScrip() {
		return (List<Scrip>)entityManager.createQuery("select s from Scrip s").getResultList();
	}
	
	@SuppressWarnings("unchecked")
	@Transactional(propagation=Propagation.MANDATORY, readOnly=true)
	public List<Scrip> getAllScrip(String type) {
		return (List<Scrip>)entityManager.createQuery("select s from Scrip s where s.type = '"+type+"'").getResultList();
	}
	
	@SuppressWarnings("unchecked")
	@Transactional(propagation=Propagation.MANDATORY, readOnly=true)
	public List<Scrip> getAllScrip(Date date){
		Query query = entityManager.createQuery("select s from Scrip s, Bar b where s.code = b.code and b.date = :date and s.type like '%Q%'");
		//Query query = entityManager.createQuery("select s from Scrip s, Bar b where s.code = b.code and b.date = :date ");
		query.setParameter("date", date);
		return (List<Scrip>)query.getResultList();
	}

}
